import Vue from "vue";
import Vuex from "vuex";

Vue.use(Vuex);

function isHave(list, info) {
  // -1 0 1 2 3 。。。。list.lenght-1
  let haveIdx = -1;
  if (list.length <= 0) return haveIdx;

  list.map((item, index) => {
    if (item.id === info.id) {
      haveIdx = index;
    }
    return item;
  });
  return haveIdx;
}

export default new Vuex.Store({
  state: {
    songList: [], // 正在播放的歌单
    currIdx: -1, // 正在播放的歌单中的歌曲的下标
    fullScreen: true, // 是否充满全屏
    likes: JSON.parse(localStorage.getItem("likes")) || [],
  },
  mutations: {
    changeLikes(state) {
      /*
       vuex数据持久化
       vuex数据刷新后会重置，为了实现数据的保存会存入到localstorage
       state初始化数据的时候从localstorage取值
       修改数据的时候先修改vuex的数据 在修改localstorage数据
      
      */
      const { likes, songList, currIdx } = state;
      // 先更新vuex数据
      const song = songList[currIdx]; //获取当前正在播放的歌曲信息
      const isHaveIdx = isHave(likes, song);
      if (isHaveIdx === -1) {
        // 当前歌曲在列表不存在
        likes.push(song);
      } else {
        likes.splice(isHaveIdx, 1);
      }
      state.likes = likes;
      // 后更新localstorage的数据
      localStorage.setItem("likes", JSON.stringify(likes));
    },
    // 修改歌单的列表
    changeSongList(state, list) {
      state.songList = list;
    },
    // 修改播放的下标
    changeCurrIdx(state, idx) {
      state.currIdx = idx;
    },
    toggleScreen(state, bool) {
      state.fullScreen = bool;
    },
  },
  getters: {
    // 当前正在播放的歌曲信息
    currSong(state) {
      const { songList, currIdx } = state;
      return songList[currIdx];
    },
    // 判断当前歌是否已喜欢
    isLike(state, getters) {
      const { likes } = state;
      const { currSong } = getters;
      const haveIdx = isHave(likes, currSong);
      return haveIdx === -1 ? false : true;
    },
  },
});
